/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.io.*;
import java.net.*;
/**
 *
 * @author Reynald
 */
public class SocketServer {
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String username;
    String password;
    
    BufferedReader br = null;
    File userdir = null;
    BufferedReader openfl = null;
    File[] filelist = null;
    
    public void listenSocket(){
        try{
            server = new ServerSocket(1235);
        }catch(Exception e){
            
        }
        
        try{
            client = server.accept();
            out = new PrintWriter(client.getOutputStream(), true);
            System.out.println(client.getRemoteSocketAddress());
        }catch(Exception e){
            
        }
        
        try{
            br = new BufferedReader(new FileReader("D:\\hoho\\userlist.txt"));
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        }catch(Exception e){
            
        }
        
        while(true){
            boolean checkuser = false;
            //server selalu menyala
            try{
                username = in.readLine();
                password = in.readLine();
                String buff;
                String dir = "";
                while(((buff = br.readLine()) != null)&(!checkuser)){
                    if((username.equals(buff.split(",")[0]))&(password.equals(buff.split(",")[1]))){
                        checkuser = true;
                    }
                    if(checkuser){
                        dir = buff.split(",")[2];
                    }
                }
                if(checkuser){//login berhasil
                    System.out.println("Login successful!");
                    //Synchronize file dimulai
                    userdir = new File(dir);
                    filelist = userdir.listFiles();
                    String fl = dir+"filelist.txt";
                    openfl = new BufferedReader(new FileReader(fl));//membuka filelist.txt
                    openfl.readLine();
                }
                if(in.readLine().equals("disconnect")){
                    client.close();
                    System.out.println("SOCKET CLOSED");
                }
            }catch(Exception e){
                
            }
        }
    }
    
    protected void finalize(){
        try{
            server.close();
            in.close();
            out.close();
        }catch(Exception e){
            
        }
    }
    
    public static void main(String[] args){
        SocketServer serv = new SocketServer();
        serv.listenSocket();
    }
}
